package zisu.rabbit.rabbitmqspring.convert;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.util.UUID;

/**
 * @Author: 蔡翔
 * @Date: 2019/8/15 16:34
 * @Version 1.0
 */
public class ImageMessageConverter implements MessageConverter {
    //转换 Object =》Message
    @Override
    public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
        throw new MessageConversionException("convert err");
    }

    //转换 Message =》 Object
    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        System.err.println("---------Image MessageConvert----------");
        Object _extName = message.getMessageProperties().getHeaders().get("extName");
        String extName = _extName ==null?"png":_extName.toString();
        byte[] body = message.getBody();
        String fileName = UUID.randomUUID().toString();
        String path = "C:/Users/wb/Desktop/rabbitImgPaht/"+fileName+"."+extName;
        File f = new File(path);
        try {
            Files.copy(new ByteArrayInputStream(body),f.toPath());
        }catch (IOException e){
            e.printStackTrace();
        }
        return f;
    }
}
